<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of account
 *
 * @author 
 */
class Account extends MY_Controller {
	public $title = 'Login';

	/**
	 *
	 * @var Codebird\Codebird 
	 */
	private $_cb;
	
	public function __construct() {
		parent::__construct();
		$this->load->library('MY_CodeBird');
		$this->_cb = MY_CodeBird::getInstance();	
	}
	
	public function login() {
		$this->render('account/login');
	}

	public function doLogin() {
		$reply = $this->_cb->oauth_requestToken(array('oauth_callback'=>
			$this->config->item('base_url') . 'account/performLogin'));
		if(!isset($reply->oauth_token)) {
		    	$this->_cb->setToken($reply->oauth_token,
						$reply->oauth_token_secret);
				$this->session->set_flashdata('failedOauthUrl',
						'<h1>FAILED</h1>');
				$this->render('account/login');
				return;
		}
		$this->_cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
		$this->session->set_userdata('oauth_token',$reply->oauth_token);
		$this->session->set_userdata('oauth_token_secret',$reply->oauth_token_secret);
		$oauthUrl = $this->_cb->oauth_authorize();
		redirect($oauthUrl);
	}

	public function performLogin() {
		if($this->session->userdata('oauth_token') == null ||
				!isset($_GET['oauth_verifier'])) {
			redirect('/login');
		}
		$this->_cb->setToken($this->session->userdata('oauth_token'),
				$this->session->userdata('oauth_token_secret'));
		$reply = $this->_cb->oauth_accessToken(array('oauth_verifier',
			$_GET['oauth_verifier']));
		if(property_exists($reply, 'user_id')) {
			$this->load->model('user');
			$user = new User();
			$userId = $user->insertUser($reply->user_id);
			$this->session->set_userdata('user_id',$userId);
		}
		redirect();
	}
}